<?php

namespace App\Http\Controllers\Admin;


use App\Model\Roles\Permission;
use Validator;
use DefaultConfig;
use Mockery\Exception;
use App\Model\Roles\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class RegisterController extends Controller
{
    /**
     * 注册
     * @param Request $request
     * @return mixed
     */
    public function register(Request $request)
    {
        $result  = $this->result();
        $requestArr = $request->all();

        try
        {
            $Validator = Validator::make($requestArr, [
                'college_name'        => 'required',
                'login_id'    => 'required | unique:users,login_id',
                'password'    => 'required | min:5',
            ]);

            if($Validator->fails())
            {
                $errors = $Validator->errors();
                $result['college_name'] = $errors->first('college_name');
                $result['login_id']    = $errors->first('login_id');
                $result['password']    = $errors->first('password');

                throw new Exception(config('result.errorRegisterMsg'), config('result.errorRegisterCode'));
            }

            $params['college_name'] = trim($requestArr['college_name']);
            $params['login_id'] = trim($requestArr['login_id']);
            $params['password'] = bcrypt(trim($requestArr['password']));
            //默认设置为普通用户
            $permission = DefaultConfig::USER;

            if(isset($requestArr['permission']))
            {
                //获取权限
                $permission = trim($requestArr['permission']);
                //映射
                $permissions = config('app.permissions');
                if (!isset($permission, $permissions))
                {
                    throw new Exception(config('result.errorSelectPermissionMsg'), config('result.errorSelectPermissionCode'));
                }
                $permission = $requestArr['permission'];
            }
            $user = new User();
            //新建用户
            $user = $user->create($params);
            $Permission = new Permission();
            //用户授权
            $Permission->setPermission($user->id, $permission);
        }
        catch (Exception $exception)
        {
            $result['errorMsg']  = $exception->getMessage();
            $result['errorCode'] = $exception->getCode();
        }

        return $result;
    }
}
